﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YasharEl.Infrastructure.EntityModel;
using System.Transactions;

namespace YasharEl.Infrastructure.PersistenceModel.EntityFramework
{
    /// <summary>
    /// Entity framework implementation of the transaction.
    /// </summary>
    public class EntityFrameworkTransaction : ITransaction
    {
        #region Constructors

        public EntityFrameworkTransaction(EntityFrameworkUnitOfWork unitOfWork)
        {
            this.UnitOfWork = unitOfWork;
            this.TransactionScope = new TransactionScope();
        }

        #endregion

        #region Protected Properties

        protected EntityFrameworkUnitOfWork UnitOfWork { get; private set; }

        protected TransactionScope TransactionScope { get; private set; }

        #endregion

        #region ITransaction Implementation

        /// <summary>
        /// Flushes unit of work and commits the transaction scope.
        /// </summary>
        public void Commit()
        {
            this.UnitOfWork.Flush();
            this.TransactionScope.Complete();
        }

        /// <summary>
        /// Rolls back transaction.
        /// Actually the transaction rollback is handled automatically with Dispose method if
        /// transaction scope was not commited.
        /// </summary>
        public void Rollback()
        {
        }

        #endregion

        #region IDisposable Implementation

        public void Dispose()
        {
            if (this.TransactionScope != null)
            {
                (this.TransactionScope as IDisposable).Dispose();
                this.TransactionScope = null;
                this.UnitOfWork = null;
            }
        }

        #endregion
    }
}
